package com.example.zhinongbao.presenter;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.example.zhinongbao.contract.OrderContract;
import com.example.zhinongbao.model.Order;
import com.example.zhinongbao.provider.ZhinongbaoContract;
import com.example.zhinongbao.provider.ZhinongbaoProvider;
import java.util.ArrayList;
import java.util.List;

public class OrderPresenter implements OrderContract.Presenter {
    private final OrderContract.View view;
    private final ContentResolver contentResolver;

    public OrderPresenter(OrderContract.View view, Context context) {
        this.view = view;
        this.contentResolver = context.getContentResolver();
    }

    @Override
    public void loadOrders(String status) {
        try {
            Uri uri = ZhinongbaoContract.Orders.CONTENT_URI;
            String selection = status.equals("全部订单") ? null : ZhinongbaoContract.Orders.COLUMN_STATUS + "=?";
            String[] selectionArgs = status.equals("全部订单") ? null : new String[]{status};
            String sortOrder = ZhinongbaoContract.Orders    .COLUMN_ORDER_DATE + " DESC";

            Cursor cursor = contentResolver.query(
                    uri,
                    null,
                    selection,
                    selectionArgs,
                    sortOrder
            );

            if (cursor != null) {
                List<Order> orders = new ArrayList<>();
                while (cursor.moveToNext()) {
                    Order order = new Order(
                            cursor.getString(cursor.getColumnIndexOrThrow(ZhinongbaoContract.Orders._ID)),
                            cursor.getString(cursor.getColumnIndexOrThrow(ZhinongbaoContract.Orders.COLUMN_PRODUCT_NAME)),
                            cursor.getString(cursor.getColumnIndexOrThrow(ZhinongbaoContract.Orders.COLUMN_STATUS)),
                            cursor.getDouble(cursor.getColumnIndexOrThrow(ZhinongbaoContract.Orders.COLUMN_PRICE)),
                            cursor.getString(cursor.getColumnIndexOrThrow(ZhinongbaoContract.Orders.COLUMN_ORDER_DATE))
                    );
                    orders.add(order);
                }
                cursor.close();

                if (orders.isEmpty()) {
                    view.showEmpty();
                } else {
                    view.showOrders(orders);
                }
            } else {
                view.showError("查询订单失败");
            }
        } catch (Exception e) {
            view.showError(e.getMessage());
        }
    }
}
